序列化操作(JSONObject)


根據給的keys不斷往內抓Object

    /*
     * Gets nested value and it is generic type
     *  TODO [!] may be throw exception about cannot cast to ...
     *
     * @param <T>        the type parameter
     * @param jsonObject the json object
     * @param keys       the keys
     * @return the nested value
     */
    public static <T> T getNestedValue(JSONObject jsonObject, String... keys) {
        Object value = jsonObject;

        for (String key : keys) {
            value = ((JSONObject) value).get(key);
        }

        return (T) value;
    }

根據給的keys不斷往內抓JSONArray

    /**
     * Gets nested value to JSONArray
     *
     * @param jsonObject the json object
     * @param keys       the keys
     * @return the nested value to json array
     */
    public static JSONArray getNestedValueToJsonArray(JSONObject jsonObject, String... keys) {
        Object value = jsonObject;
        JSONArray array =null;
        for (String key : keys) {
            value = ((JSONObject) value).get(key);
        }
        if (value instanceof JSONArray) {
            array = (JSONArray) value;
        }
        if (value instanceof JSONObject) {
            array = new JSONArray();
            array.put(value);
        }
        return  array;
    }

從路徑反序列化成物件

    /**
     * Get dto from json file t.
     *
     * @param <T>  the type parameter
     * @param path the path
     * @param type the type
     * @return the t
     */
    public static <T> T getDtoFromJsonFile(String path, Type type){
        try {
            return new Gson().fromJson(new FileReader(path), type);
        }catch (FileNotFoundException e){
            throw new JsonParseException("path or type is invalid");
        }
    }
    /*
     * 根據JSONObject all key 看是否有 keyMain
     */
    public static boolean findKey(JSONObject obj, String keyMain){
        AtomicBoolean foundKeyMainFlag = new AtomicBoolean(false);
        Set<String> keys = new HashSet<>();
        JsonUtil.getAllKeys(obj, keys);
        Optional.of(keys).ifPresent(keyList -> foundKeyMainFlag.set(keyList.stream().anyMatch(key -> keyMain.equalsIgnoreCase(key))));
        if (Boolean.FALSE.equals(foundKeyMainFlag.get())) {
            return false;
        }
        return true;
    }


    /*
     * 根據obj 並用keyMain去新增
     */
    public static JSONObject createByKeyMain(JSONObject obj, String keyMain, String jsonString){
        return obj.put(keyMain,new JSONObject(jsonString));
    }
    /*
     * 根據keyMain找到置換處(遍歷) 並用jsonString去更新value
     * keyMain若不存在則不更新
     */
    public static JSONObject update(JSONObject obj, String keyMain, String jsonString){

        // We need to know keys of Jsonobject
        Iterator iterator = obj.keys();
        String key;
        while (iterator.hasNext()) {
            key = (String) iterator.next();
            if (key.equals(keyMain)) {
                // put new value
                obj.put(key, new JSONObject(jsonString));
                return obj;
            }

            // if it's jsonobject
            if (obj.optJSONObject(key) != null) {
                update(obj.getJSONObject(key), keyMain, jsonString);
            }

            // if it's jsonarray
            if (obj.optJSONArray(key) != null) {
                JSONArray jArray = obj.getJSONArray(key);
                for (int i = 0; i < jArray.length(); i++) {
                    update(jArray.getJSONObject(i), keyMain, jsonString);
                }
            }
        }
        return obj;
    }

上述方法的私有方法

    private static Set<String> getAllKeys(JSONObject json) {
        return getAllKeys(json, new HashSet<>());
    }

    private static Set<String> getAllKeys(JSONArray arr) {
        return getAllKeys(arr, new HashSet<>());
    }

    private static Set<String> getAllKeys(JSONArray arr, Set<String> keys) {
        for (int i = 0; i < arr.length(); i++) {
            Object obj = arr.get(i);
            if (obj instanceof JSONObject) keys.addAll(getAllKeys(arr.getJSONObject(i)));
            if (obj instanceof JSONArray) keys.addAll(getAllKeys(arr.getJSONArray(i)));
        }

        return keys;
    }

    private static Set<String> getAllKeys(JSONObject json, Set<String> keys) {
        for (String key : json.keySet()) {
            if (json.optJSONObject(key)!=null) keys.addAll(getAllKeys(json.getJSONObject(key)));
            if (json.optJSONArray(key)!=null) keys.addAll(getAllKeys(json.getJSONArray(key)));
        }

        keys.addAll(json.keySet());
        return keys;
    }
#java #jsonobject







你可能感興趣的文章

數據分析師的末日?GPT-4 的新功能 - code interpreter

數據分析師的末日?GPT-4 的新功能 - code interpreter

相見恨晚的 chrome 插件 — Octotree - GitHub code tree

相見恨晚的 chrome 插件 — Octotree - GitHub code tree

Python 爬取 Google 新聞

Python 爬取 Google 新聞






留言討論